package com.tangbuzhi.chm.ui;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.tangbuzhi.chm.ChmApplication;
import com.tangbuzhi.chm.Entity;
import com.tangbuzhi.chm.EntityDao;
import com.tangbuzhi.chm.R;
import com.tangbuzhi.chm.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

/**
 * http://git.oschina.net/tangbuzhi
 *
 * @author Tangbuzhi
 * @version V2.0
 * @Package com.tangbuzhi.chm.ui
 * @Description: ${TODO}
 * @date: 2017/9/12
 */
public class DaoActivity extends AppCompatActivity {

    private TextView tv_id;
    private EditText et_name;
    private EditText et_age;
    private EditText et_score;
    private ListView lv_list;
    private Cursor cursor;
    private long id;
    private String name;
    private Integer age;
    private Double score;
    private DaoAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dao);
        initView();
        initCursor();
        initAdapter(queryAll());
    }

    private void initView() {
        tv_id = (TextView) findViewById(R.id.tv_id);
        et_name = (EditText) findViewById(R.id.et_name);
        et_age = (EditText) findViewById(R.id.et_age);
        et_score = (EditText) findViewById(R.id.et_score);
        lv_list = (ListView) findViewById(R.id.lv_list);
    }

    private void initCursor() {
        String orderBy = EntityDao.Properties.Id.columnName + " ASC";
        cursor = getDb().query(getEntityDao().getTablename(), getEntityDao().getAllColumns(), null, null, null, null, orderBy);
    }

    private SQLiteDatabase getDb() {
        return ((ChmApplication) this.getApplication()).getDb();
    }

    private EntityDao getEntityDao() {
        return ((ChmApplication) this.getApplication()).getDaoSession().getEntityDao();
    }

    private void initAdapter(List<Entity> lists) {
        adapter = new DaoAdapter(lists);
        lv_list.setAdapter(adapter);
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Entity item = adapter.getItem(i);
                tv_id.setText("id: " + item.getId());
                et_name.setText(item.getName());
                et_age.setText(item.getAge() + "");
                et_score.setText(item.getScore() + "");
            }
        });
    }

    public void add(View view) {
        name = et_name.getText().toString().trim();
        age = Integer.parseInt(et_age.getText().toString().trim());
        score = Double.parseDouble(et_score.getText().toString().trim());
        if (!TextUtils.isEmpty(name)) {
            Entity entity = new Entity(null, name, age, score);
            getEntityDao().insert(entity);//面向对象添加表数据
        } else {
            ToastUtil.showToast(this, "name不能为空");
        }
        initAdapter(queryAll());
    }

    public void delete(View view) {
        id = Long.valueOf(tv_id.getText().toString().substring(3).trim());
        /*根据id删除*/
        getEntityDao().deleteByKey(id);
        initAdapter(queryAll());
    }

    public void update(View view) {
        id = Long.valueOf(tv_id.getText().toString().substring(3).trim());
        name = et_name.getText().toString().trim();
        age = Integer.parseInt(et_age.getText().toString().trim());
        score = Double.parseDouble(et_score.getText().toString().trim());
        Entity entity = new Entity(id, name, age, score);
        getEntityDao().update(entity);
        initAdapter(queryAll());
    }

    public void query_name(View view) {
        name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showToast(this, "name不能为空");
            return;
        }
        Query<Entity> query = getEntityDao().queryBuilder()
                .where(EntityDao.Properties.Name.eq(name))
                .orderAsc(EntityDao.Properties.Id)
                .build();
        //查询结果以List返回List
        List<Entity> count = query.list();
        if (count.size() > 0) {
            ToastUtil.showToast(this, count.size() + "条数据被查到");
            initAdapter(count);
        } else {
            ToastUtil.showToast(this, "没有找到name=" + name + "的足迹");
        }
    }

    public void query_all(View view) {
        QueryBuilder<Entity> queryBuilder = getEntityDao().queryBuilder();
        List<Entity> list = queryBuilder.list();
        if (list.size() <= 0) {
            ToastUtil.showToast(this, "没有数据");
            return;
        }
        initAdapter(list);
    }

    public void query_age(View view) {
        String trim = et_age.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            ToastUtil.showToast(this, "age不能为空");
            return;
        }
        age = Integer.parseInt(trim);
        Query<Entity> query = getEntityDao().queryBuilder()
                .where(EntityDao.Properties.Age.eq(age))
                .orderAsc(EntityDao.Properties.Id)
                .build();
        List<Entity> count = query.list();
        if (count.size() > 0) {
            ToastUtil.showToast(this, count.size() + "条数据被查到");
            initAdapter(count);
        } else {
            ToastUtil.showToast(this, "没有找到age=" + age + "的足迹");
        }
    }

    public void query_score(View view) {
        String trim = et_score.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            ToastUtil.showToast(this, "score不能为空");
            return;
        }
        score = Double.parseDouble(trim);
        Query<Entity> query = getEntityDao().queryBuilder()
                .where(EntityDao.Properties.Score.eq(score))
                .orderAsc(EntityDao.Properties.Id)
                .build();
        List<Entity> count = query.list();
        if (count.size() > 0) {
            ToastUtil.showToast(this, count.size() + "条数据被查到");
            initAdapter(count);
        } else {
            ToastUtil.showToast(this, "没有找到score=" + score + "的足迹");
        }
    }

    private List<Entity> queryAll() {
        QueryBuilder<Entity> queryBuilder = getEntityDao().queryBuilder();
        List<Entity> list = queryBuilder.list();
        return list;
    }

    private class DaoAdapter extends BaseAdapter {
        List<Entity> lists = new ArrayList<>();

        public DaoAdapter(List<Entity> lists) {
            this.lists = lists;
        }

        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Entity getItem(int i) {
            return lists.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            DaoViewHolder holder;
            if (view == null) {
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_dao, viewGroup, false);
                holder = new DaoViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (DaoViewHolder) view.getTag();
            }
            holder.id.setText(lists.get(i).getId() + "");
            holder.name.setText(lists.get(i).getName() + "");
            holder.age.setText(lists.get(i).getAge() + "");
            holder.score.setText(lists.get(i).getScore() + "");
            return view;
        }

        private class DaoViewHolder {
            private TextView id, name, age, score;

            public DaoViewHolder(View itemView) {
                id = itemView.findViewById(R.id.id);
                name = itemView.findViewById(R.id.name);
                age = itemView.findViewById(R.id.age);
                score = itemView.findViewById(R.id.score);
            }
        }
    }
}
